package com.sky.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private static final String INSERT_TIME = "createTime";

    private static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("自动注入字段");
        // 创建createTime
        this.insertDate(INSERT_TIME, metaObject);
        // 创建updateTime
        this.insertDate(UPDATE_TIME, metaObject);
        log.info("自动注入字段完成");
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新或创建updateTime
        this.updateDate(UPDATE_TIME, metaObject);

    }

    // 创建时间字段
    private void insertDate(String filedName, MetaObject metaObject) {
        // 创建createTime
        if (this.isValue(filedName, metaObject)) {
            this.strictInsertFill(metaObject, filedName, LocalDateTime.class, LocalDateTime.now());
            //this.strictInsertFill(metaObject, filedName, LocalDate::new, Date.class);
        }
    }

    // 更新时间字段
    private void updateDate(String filedName, MetaObject metaObject) {
        if (this.isValue(filedName, metaObject)) {
            Object fieldValByName = getFieldValByName(filedName, metaObject);
            if (fieldValByName != null) {
                this.setFieldValByName(filedName, new Date(), metaObject);
            }
            this.strictUpdateFill(metaObject, filedName, LocalDateTime.class, LocalDateTime.now());
            //this.strictUpdateFill(metaObject, filedName, Date::new, Date.class);
        }
    }

    // 值是否存在
    private boolean isValue(String filedName, MetaObject metaObject) {
        // 值是否存在
        boolean value = metaObject.hasGetter(filedName);
        // 字段存在，值为空
        if (value
                && ObjectUtils.isEmpty(metaObject.getValue(filedName))) {
            return true;
        }
        return false;
    }

}